package com.suyang.syt.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suyang.syt.context.BeanFactoryContext;
import com.suyang.syt.dao.interfaces.BannerDao;
import com.suyang.syt.dao.interfaces.PicDao;
import com.suyang.syt.dao.interfaces.UserDao;
import com.suyang.syt.model.Pic;
import com.suyang.syt.model.User;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.PagerEasyUI;
import com.suyang.syt.model.dto.PicDTO;
import com.suyang.syt.service.interfaces.PicService;
import com.suyang.syt.util.EmptyUtil;

@Service
public class PicServiceImpl implements PicService {

	@Autowired
	private PicDao picDao;
	@Autowired
	private BannerDao bannerDao;
	@Autowired
	private UserDao userDao;

	@Override
	public List<Pic> findByBanner(Long bid) throws Exception {
		return picDao.findByBanner(bid);
	}

	@Override
	public PagerEasyUI<PicDTO> listByEasyUI(int page, int rows, String sort, String order, String createDate1, String createDate2, String checkName, long bid, String status) throws Exception {

		StringBuilder hql = new StringBuilder(" from Pic pc where 1=1  ");//
		if (EmptyUtil.isNotEmpty(createDate1)) {
			hql.append(" and pc.createTime>='").append(createDate1).append("'");
		}
		if (EmptyUtil.isNotEmpty(createDate2)) {
			hql.append(" and pc.createTime<='").append(createDate2).append("'");
		}
		if (EmptyUtil.isNotEmpty(checkName)) {
			hql.append(" and pc.name like '%").append(checkName).append("%'");
		}
		if (EmptyUtil.isNotEmpty(status)) {
			hql.append(" and pc.status = ").append(Integer.parseInt(status));
		}
		if (bid != 0) {
			hql.append(" and pc.bid = ").append(bid);
		}
		if (EmptyUtil.isNotEmpty(sort)) {
			hql.append(" order by pc.").append(sort);
		}
		if (EmptyUtil.isNotEmpty(order)) {
			hql.append(" ").append(order);
		}
		PagerEasyUI<PicDTO> easyUIPager = new PagerEasyUI<PicDTO>();
		List<Pic> pics = picDao.findByEasyUI(hql.toString(), page, rows);
		List<PicDTO> picDTOList = new ArrayList<PicDTO>();
		PicDTO picDTO = null;
		for (Pic pc : pics) {
			picDTO = new PicDTO(pc);
			// teacherDTO.setTeacherReplys(teacherReplyDao.list("from TeacherReply tr where tr.tid=?",
			// teacher.getId()));//教师评价的列表信息
			picDTOList.add(picDTO);
		}
		easyUIPager.setRows(picDTOList);
		easyUIPager.setTotal((Long) picDao.queryByHql(" select count(*)" + hql));
		return easyUIPager;
	}

	@Override
	public AjaxObj addPic(PicDTO picDTO) throws Exception {
		if (picDTO != null && picDTO.getBid() != 0) {
			// 添加图片不为空，并且bid轮换图不为空
			Pic pc = new Pic();
			// logo图像
			String path = picDTO.getPath();
			if (path.indexOf("logo_px.png") < 0) {
				pc.setPath(path);
			}
			pc.setBid(picDTO.getBid());
			pc.setCreateName(picDTO.getCreateName());
			pc.setCreateTime(picDTO.getCreateTime());
			pc.setName(picDTO.getName());
			pc.setStatus(picDTO.getStatus());
			pc.setOrderIndex(0);
			pc.setPicLikeNums(picDTO.getPicLikeNums());
			picDao.add(pc);
			return new AjaxObj(1, "添加照片成功！");
		}
		return new AjaxObj(0, "未能成功添加照片！");
	}

	@Override
	public AjaxObj deletePics(String ids) throws Exception {
		if (EmptyUtil.isNotEmpty(ids)) {
			// 图片的id
			// 根据图片id得到要删除图片的列表
			List<Pic> lt = picDao.findByids(ids);
			if (lt.size() != 0 && lt != null) {
				// 判断如图片列表不为空
				// 获取图片的banner中的id
				long bid = lt.get(0).getBid();
				// 根据图片ids 删除照片
				picDao.deleteByids(ids);
				// 根据被删除图片的banner的id查找在banner中是否还有图片存在
				List<Pic> ltt = picDao.findByBanner(bid);
				if (ltt.size() == 0 || ltt == null) {
					// 如果在pic中没有该banner的图片信息，则删除banner图中的关于该童星的轮换信息
					// 删除banner图中的轮换信息
					bannerDao.delete(bid);
				}
			}
		}
		return new AjaxObj(1, "成功的删除了照片");
	}

	@Override
	public AjaxObj updatePic(PicDTO picDTO) throws Exception {
		if (picDTO != null && picDTO.getBid() != 0) {
			// 添加图片不为空，并且bid轮换图不为空
			// logo图像
			Pic pc = picDao.load(picDTO.getId());
			String path = picDTO.getPath();
			if (path.indexOf("logo_px.png") < 0) {
				pc.setPath(path);
			}
			pc.setBid(picDTO.getBid());
			pc.setModifyName(picDTO.getModifyName());
			pc.setModifyTime(picDTO.getModifyTime());
			pc.setName(picDTO.getName());
			pc.setStatus(picDTO.getStatus());
			pc.setOrderIndex(0);
			pc.setPicLikeNums(picDTO.getPicLikeNums());
			picDao.update(pc);
			return new AjaxObj(1, "更新照片成功！");
		}
		return new AjaxObj(0, "未能成功更新照片！");
	}

	@Override
	public AjaxObj addPicLike(String id) throws Exception {
		if (EmptyUtil.isNotEmpty(id)) {
			Pic pc = picDao.load(Long.parseLong(id));
			if (pc != null) {

				pc.setPicLikeNums(pc.getPicLikeNums() + 1);
				picDao.update(pc);
				return new AjaxObj(1, "点赞成功！");

			} else {
				return new AjaxObj(0, "该照片不存在，无法点赞！");
			}
		}
		return new AjaxObj(0, "点赞失败！");
	}

	@Override
	public List<Pic> findAll() throws Exception {
		List<Pic> lt = picDao.findAll();
		List<User> user = userDao.findAllUser();
		for (User user2 : user) {
			Pic pc = new Pic();
			pc.setPath(user2.getIcon());
			lt.add(pc);
		}
		return lt;
	}

	// 每次递归的标识
	private static int k = 0;
	// 最后返回值的标识
	private static int l = 0;

	// 递归遍历文件
	public int FindFile(String s) {
		File file = new File(s);
		boolean flag = true;
		int m = 0;// 删除成功 标识
		int n = 0;// 删除失败标识
		if (file.isDirectory()) {
			String[] files = file.list();
			List<Pic> lt;
			try {
				lt = findAll();
				for (String temp : files) {
					String newstr = s + "\\" + temp;
					if (new File(newstr).isFile()) {
						String url = newstr.substring(newstr.lastIndexOf("\\") + 1, newstr.trim().length()).trim();// 获取文件中的图片路径名称
						for (int i = 0; i < lt.size(); i++) {
							Pic pic = lt.get(i);
							if (EmptyUtil.isNotEmpty(pic.getPath())) {// 除去为空的图片path
								if (url.equals(pic.getPath()) || url.substring(0, url.indexOf(".")).equals(pic.getPath().substring(0, pic.getPath().indexOf(".")))) {
									flag = true;
									break;
								} else {
									flag = false;
								}
							}
						}
						if (!flag) {
							File file2 = new File(newstr);
							boolean mm = file2.delete();// 删除是否成功
							if (mm) {
								m += 1;// 删除成功为标识 1
							} else {
								n += -1;// 删除失败为标识 -1
							}
						}
					} else {
						FindFile(newstr);
					}
				}
				// 每次递归 后设置删除图片的返回值
				if (m > 0 && n == 0) {
					k = 1;
				} else if (m == 0 && n < 0) {
					k = -1;
				} else {
					k = 0;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (k >= 0) {
			l += k;
		}
		return l;
	}

	@Override
	public void deletePicFiles() {
		String path = BeanFactoryContext.getRealPath() + "/resources/upload";
		int i = FindFile(path);
		l = 0;
		if (i > 0) {
			System.out.println("清理垃圾图片成功！");
		} else if (i == 0) {
			System.out.println("没有垃圾图片可供清理！");
		} else {
			System.out.println("清理垃圾图片失败！");
		}
	}
}
